<template>
  <div class="organization-switcher">
    <a-button 
      type="text" 
      @click="showModal = true"
      class="switch-btn"
    >
      <template #icon>
        <SwapOutlined />
      </template>
      <span class="btn-text">切换机构</span>
    </a-button>

    <a-modal
      v-model:open="showModal"
      title="选择机构"
      :width="800"
      :footer="null"
      @cancel="showModal = false"
    >
      <div class="organization-list">
        <a-input
          v-model:value="searchKeyword"
          placeholder="搜索机构名称或账号"
          class="search-input"
          allow-clear
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>

        <a-tabs v-model:activeKey="activeTabKey" class="organization-tabs">
          <a-tab-pane key="caimeng" tab="审核委案权限">
            <div class="organization-grid">
              <div
                v-for="org in filteredOrganizationsByPermission('caimeng')"
                :key="org.account"
                class="organization-item"
                :class="{ active: selectedOrg?.account === org.account }"
                @click="selectOrganization(org)"
              >
                <div class="org-info">
                  <div class="org-name">{{ org.name }}</div>
                  <div class="org-account">{{ org.account }}</div>
                </div>
                <div class="org-status">
                  <CheckCircleOutlined v-if="selectedOrg?.account === org.account" />
                </div>
              </div>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="caimengmeng" tab="分案权限">
            <div class="organization-grid">
              <div
                v-for="org in filteredOrganizationsByPermission('caimengmeng')"
                :key="org.account"
                class="organization-item"
                :class="{ active: selectedOrg?.account === org.account }"
                @click="selectOrganization(org)"
              >
                <div class="org-info">
                  <div class="org-name">{{ org.name }}</div>
                  <div class="org-account">{{ org.account }}</div>
                </div>
                <div class="org-status">
                  <CheckCircleOutlined v-if="selectedOrg?.account === org.account" />
                </div>
              </div>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="default" tab="录案权限">
            <div class="organization-grid">
              <div
                v-for="org in filteredOrganizationsByPermission('default')"
                :key="org.account"
                class="organization-item"
                :class="{ active: selectedOrg?.account === org.account }"
                @click="selectOrganization(org)"
              >
                <div class="org-info">
                  <div class="org-name">{{ org.name }}</div>
                  <div class="org-account">{{ org.account }}</div>
                </div>
                <div class="org-status">
                  <CheckCircleOutlined v-if="selectedOrg?.account === org.account" />
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>

        <!-- TOTP验证码显示区域 -->
        <div class="totp-section" v-if="selectedOrg">
          <div class="totp-info">
            <div class="totp-label">TOTP验证码:</div>
            <div class="totp-code">{{ currentTOTPCode }}</div>
            <div class="totp-countdown">剩余时间: {{ countdown }}秒</div>
          </div>
        </div>

        <div class="modal-footer">
          <a-button @click="showModal = false">取消</a-button>
          <a-button 
            type="primary" 
            @click="handleLogin"
            :disabled="!selectedOrg"
            :loading="isLogging"
          >
            登录
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { 
  SwapOutlined, 
  SearchOutlined, 
  CheckCircleOutlined 
} from '@ant-design/icons-vue';
import { loginSms } from '../server/api';
import { type Organization } from '../config/organizations';
import { organizationManager } from '../config/organization-manager';
import { useUserStore } from '../store/user';
// @ts-ignore
import '../utils/crypto-js.js';
// 直接导入otplib库（polyfill插件会自动处理Buffer、process、crypto等）
import { authenticator } from 'otplib';

// 路由
const router = useRouter();

// 声明全局类型
declare global {
  var CryptoJS: any;
  var global: any;
}

// 用户状态管理
const userStore = useUserStore();

// 获取CryptoJS实例
const getCryptoJS = () => {
  if (typeof globalThis !== 'undefined' && (globalThis as any).CryptoJS) {
    return (globalThis as any).CryptoJS;
  }
  if (typeof window !== 'undefined' && (window as any).CryptoJS) {
    return (window as any).CryptoJS;
  }
  if (typeof global !== 'undefined' && (global as any).CryptoJS) {
    return (global as any).CryptoJS;
  }
  throw new Error('CryptoJS未加载，请检查crypto-js.js是否正确导入');
};

// 响应式数据
const showModal = ref(false);
const searchKeyword = ref('');
const selectedOrg = ref<Organization | null>(null);
const isLogging = ref(false);

// 当前激活的tab
const activeTabKey = ref('caimeng');

// TOTP相关数据
const currentTOTPCode = ref('');
const countdown = ref(30);
const totpInterval = ref<number | null>(null);
const MY_SECRET = 'vuixppgt3kx3fbtjp2pzgfzzccxqkv7q';

// 按权限过滤机构列表
const filteredOrganizationsByPermission = (permission: string) => {
  const allOrgs = organizationManager.getAllOrganizations();
  const filtered = allOrgs.filter(org => org.menuPermissions === permission);
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    return filtered.filter(org => 
      org.name.toLowerCase().includes(keyword) || 
      org.account.toLowerCase().includes(keyword)
    );
  }
  
  return filtered;
};

// 更新TOTP验证码（直接使用otplib）
const updateTOTP = async () => {
  try {
    // 直接使用otplib的authenticator生成TOTP
    const code = authenticator.generate(MY_SECRET);
    currentTOTPCode.value = code;
  } catch (error) {
    console.error('生成TOTP验证码失败:', error);
    currentTOTPCode.value = '错误: ' + (error as Error).message;
  }
};

// 启动TOTP定时器
const startTOTPTimer = () => {
  // 清除现有定时器
  if (totpInterval.value) {
    clearInterval(totpInterval.value);
  }
  
  // 立即更新一次
  updateTOTP();
  
  // 设置定时器，每30秒更新一次
  totpInterval.value = setInterval(() => {
    updateTOTP();
  }, 30000);
  
  // 设置倒计时
  const updateCountdown = () => {
    const now = Date.now();
    const remaining = 30 - (Math.floor(now / 1000) % 30);
    countdown.value = remaining;
  };
  
  updateCountdown();
  const countdownInterval = setInterval(updateCountdown, 1000);
  
  // 30秒后清除倒计时定时器
  setTimeout(() => {
    clearInterval(countdownInterval);
  }, 30000);
};

// 停止TOTP定时器
const stopTOTPTimer = () => {
  if (totpInterval.value) {
    clearInterval(totpInterval.value);
    totpInterval.value = null;
  }
};

// 选择机构
const selectOrganization = (org: Organization) => {
  selectedOrg.value = org;
  // 选择机构后立即更新TOTP验证码
  updateTOTP();
  startTOTPTimer();
};

// 监听tab切换，自动选中第一个机构
watch(activeTabKey, (newTabKey) => {
  const orgs = filteredOrganizationsByPermission(newTabKey);
  if (orgs.length > 0) {
    selectOrganization(orgs[0]);
  } else {
    selectedOrg.value = null;
  }
}, { immediate: true });

// 监听搜索关键词变化，自动选中第一个搜索结果
watch(searchKeyword, () => {
  const orgs = filteredOrganizationsByPermission(activeTabKey.value);
  if (orgs.length > 0) {
    selectOrganization(orgs[0]);
  } else {
    selectedOrg.value = null;
  }
});


// 处理登录
const handleLogin = async () => {
  if (!selectedOrg.value) {
    message.warning('请选择一个机构');
    return;
  }

  try {
    isLogging.value = true;
    
    // 调用登录函数，实现完整的机构切换登录流程
    const result = await loginToOrganization(selectedOrg.value);
    
    message.success(`已成功切换到 ${selectedOrg.value.name}，用户状态已更新`);
    console.log('机构切换登录成功:', result);
    showModal.value = false;

    router.replace('/');
    // @ts-ignore
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  } catch (error) {
    console.error('登录失败:', error);
    message.error('登录失败，请重试');
  } finally {
    isLogging.value = false;
  }
};

// 登录函数
const loginToOrganization = async (org: Organization) => {
  try {
    // 使用当前显示的TOTP验证码
    const code = currentTOTPCode.value;
    
    if (!code || code.startsWith('错误:')) {
      throw new Error('TOTP验证码无效，请重新选择机构');
    }
    
    // 加密密码
    const encryptedPassword = getCryptoJS().MD5(org.password).toString();
    console.log('密码加密:', { original: org.password, encrypted: encryptedPassword });
    
    // 调用登录接口
    const response = await loginSms({
      accountNo: org.account,
      pwd: encryptedPassword,
      code: code,
      tsToken: null
    });
    console.log('登录接口返回:', response);
    
    // @ts-ignore
    if (response.code === '200' && response.success) {
      // 登录成功，停止TOTP定时器
      stopTOTPTimer();
      console.log('登录成功:', response.result);
      console.log('用户信息:', {
        userName: response.result.userName,
        tsToken: response.result.tsToken,
        currentAuthority: response.result.currentAuthority,
        status: response.result.status,
        initialPassword: response.result.initialPassword
      });
      
      // 实现完整的登录流程：设置tsToken，重新获取个人信息
      await handleOrganizationLogin(response.result);
      
      return response.result;
    } else {
      throw new Error(response.message || '登录失败');
    }
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

/**
 * 处理机构登录后的完整流程
 * 实现与LoginForm.vue中handleLogin函数相同的功能
 */
const handleOrganizationLogin = async (loginData: any) => {
  try {
    console.log('开始处理机构登录流程...');
    
    // 1. 设置tsToken到localStorage，用于API请求
    localStorage.setItem('tsToken', loginData.tsToken);
    console.log('tsToken已设置:', loginData.tsToken);
    
    // 2. 调用userStore的login方法，实现完整的登录流程
    // 这会调用getCurrentUserInfo验证tsToken并获取用户信息
    await userStore.login({ tsToken: loginData.tsToken });
    
    console.log('机构登录流程完成，用户状态已更新');
    console.log('当前用户信息:', userStore.userInfo);
    console.log('当前tsToken:', userStore.tsToken);
    console.log('登录状态:', userStore.isLoggedIn);
    
    // 3. 跳转到首页，关闭其他页面
    console.log('跳转到首页...');
    router.replace('/');

    setTimeout(() => {
      window.location.reload();
    }, 1000);
    
  } catch (error) {
    console.error('机构登录流程失败:', error);
    // 如果获取用户信息失败，清除可能已保存的数据
    localStorage.removeItem('tsToken');
    localStorage.removeItem('userInfo');
    throw error;
  }
};

// 组件挂载时
onMounted(() => {
  // 测试密码加密功能
  testPasswordEncryption();
});

// 测试密码加密功能
const testPasswordEncryption = () => {
  try {
    // 测试几个常见密码的加密
    const testPasswords = ['pt2021', 'Caimeng1013', 'test123'];
    console.log('=== 密码加密测试 ===');
    testPasswords.forEach(password => {
      const encrypted = getCryptoJS().MD5(password).toString();
      console.log(`${password} -> ${encrypted}`);
    });
    console.log('=== 密码加密测试完成 ===');
  } catch (error) {
    console.error('密码加密测试失败:', error);
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  stopTOTPTimer();
});

// 暴露给父组件的方法
defineExpose({
  selectOrganization,
  handleLogin,
  updateTOTP,
  startTOTPTimer,
  stopTOTPTimer
});
</script>

<style scoped>
.organization-switcher {
  display: inline-block;
}

.switch-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1890ff;
  border: none;
  background: transparent;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.switch-btn:hover {
  background-color: #f0f8ff;
  color: #40a9ff;
}

.btn-text {
  font-size: 14px;
}

.organization-list {
  padding: 16px 0;
}

.search-input {
  margin-bottom: 16px;
}

.organization-tabs {
  margin-bottom: 16px;
}

.organization-tabs :deep(.ant-tabs-content-holder) {
  max-height: 300px;
  overflow-y: auto;
}

.organization-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

/* 响应式布局 */
@media (min-width: 1200px) {
  .organization-grid {
    grid-template-columns: repeat(6, 1fr);
  }
}

@media (min-width: 1400px) {
  .organization-grid {
    grid-template-columns: repeat(8, 1fr);
  }
}

@media (max-width: 768px) {
  .organization-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.organization-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px 4px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
  text-align: center;
  min-height: 60px;
}

.organization-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.organization-item.active {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.org-info {
  flex: 1;
  width: 100%;
}

.org-name {
  font-size: 12px;
  font-weight: 500;
  color: #262626;
  margin-bottom: 2px;
  line-height: 1.2;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.org-account {
  font-size: 10px;
  color: #8c8c8c;
  line-height: 1.2;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.org-status {
  color: #1890ff;
  font-size: 14px;
  margin-top: 4px;
}

.totp-section {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.totp-info {
  text-align: center;
}

.totp-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.totp-code {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  font-family: 'Courier New', monospace;
  letter-spacing: 2px;
  margin-bottom: 8px;
  padding: 8px 16px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  display: inline-block;
}

.totp-countdown {
  font-size: 12px;
  color: #999;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 滚动条样式 */
.organization-grid::-webkit-scrollbar {
  width: 6px;
}

.organization-grid::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.organization-grid::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.organization-grid::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
